package com.itheima.common;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;


/**
 * 自定义元数据对象处理器
 */

@Component   //让spring框架管理
@Slf4j
public class MyMetaObjecthandler implements MetaObjectHandler {
    /**
     * 插入添加操作，自动填充
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) { //当我们执行insert语句当时候才会执行
        log.info("公共字段自动填充[insert]...");
        log.info(metaObject.toString());
        metaObject.setValue("createTime", LocalDateTime.now());
        metaObject.setValue("updateTime", LocalDateTime.now());
        metaObject.setValue("createUser", BaseContext.getCurrentId());
        metaObject.setValue("updateUser", BaseContext.getCurrentId());

    }

    /**
     * 更新，修改操作，自动填充
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {//当我们执行更新的时候才会执行
        log.info("公共字段自动填充[update]...");
        log.info(metaObject.toString());

        Long id = Thread.currentThread().getId();
        log.info("线程id为:{}",id);
        metaObject.setValue("updateTime", LocalDateTime.now());
        metaObject.setValue("updateUser", BaseContext.getCurrentId());
    }
}
